<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-tag"></i> 社区分类管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 搜索栏 -->
    <div class="container">
      <div class="handle-box">
        <el-input v-model="searchForm.categoryName" placeholder="社区分类名称" class="handle-input mr10" clearable />
        <!-- <el-input v-model="searchForm.categoryId" placeholder="社区分类ID" class="handle-input mr10" clearable />
        <el-date-picker v-model="searchForm.createTime" type="date" placeholder="创建时间" class="handle-input mr10"
          clearable /> -->
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="showAddCategory">新增社区分类</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" border class="table" ref="categoryTable" header-cell-class-name="table-header">
        <el-table-column prop="id" label="社区分类ID" width="120" />
        <el-table-column prop="categoryName" label="社区分类名称" />
        <!-- <el-table-column prop="categoryImage" label="社区分类图" >
          <template #default="scope">
            <el-image v-if="scope.row.categoryImage" :src="scope.row.categoryImage"
              style="width: 60px; height: 60px; border-radius: 4px;" fit="cover"
              :preview-src-list="[scope.row.categoryImage]" />
            <span v-else>-</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="createTime" label="创建时间" >
          <template #default="scope">
            {{ scope.row.createTime ? dateFormat(scope.row.createTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="showEditCategory(scope.row)">编辑</el-button>
            <el-button type="text" class="red" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
        </el-pagination>
      </div>
    </div>

    <!-- 新增/编辑社区分类弹窗 -->
    <el-dialog v-model="categoryDialog.visible" :title="categoryDialog.isEdit ? '编辑社区分类' : '新增社区分类'" width="600px">
      <el-form :model="categoryDialog.form" :rules="categoryRules" ref="categoryForm" label-width="120px">
        <el-form-item label="社区分类名称" prop="categoryName">
          <el-input v-model="categoryDialog.form.categoryName" placeholder="请输入社区分类名称" />
        </el-form-item>
        <!-- <el-form-item label="社区分类图" prop="categoryImage">
          <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeImageUpload"
            :http-request="handleImageUpload">
            <img v-if="categoryDialog.form.categoryImage" :src="categoryDialog.form.categoryImage" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <i v-if="categoryDialog.form.categoryImage" class="el-icon-close close-btn" @click.stop="removeImage"></i>
          </el-upload>
          <div class="form-tip">建议上传尺寸为 200x200 像素的图片</div>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <el-button @click="categoryDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveCategory">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import { getForumCategories, addForumCategory, updateForumCategory, deleteForumCategory } from "@/api/content";
import { upload } from "@/api/index";

export default {
  name: "CommunityClassification",
  data() {
    return {
      searchForm: {
        categoryName: "",
        categoryId: "",
        createTime: "",
      },
      tableData: [],
      // 分页相关
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 社区分类弹窗
      categoryDialog: {
        visible: false,
        isEdit: false,
        editId: null,
        form: {
          categoryName: "",
          categoryImage: "",
        },
      },
      // 表单验证规则
      categoryRules: {
        categoryName: [
          { required: true, message: '请输入社区分类名称', trigger: 'blur' },
          { min: 1, max: 50, message: '社区分类名称长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        categoryImage: [
          { required: true, message: '请上传社区分类图', trigger: 'change' }
        ]
      }
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    dateFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getData();
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getData();
    },
    buildSearchParams() {
      const params = {
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage
      };

      if (this.searchForm.categoryName) {
        params.categoryName = this.searchForm.categoryName;
      }
      if (this.searchForm.categoryId) {
        params.id = this.searchForm.categoryId;
      }
      if (this.searchForm.createTime) {
        params.createTime = moment(this.searchForm.createTime).format('YYYY-MM-DD');
      }

      return params;
    },
    async getData() {
      try {
        const params = this.buildSearchParams();
        const response = await getForumCategories(params);

        if (response && response.data) {
          this.tableData = response.data.rows || response.data;

          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total;
          }
        }
      } catch (error) {
        console.error('获取社区分类数据失败:', error);
        this.$message.error('获取社区分类数据失败');
      }
    },
    showAddCategory() {
      this.categoryDialog.visible = true;
      this.categoryDialog.isEdit = false;
      this.categoryDialog.editId = null;
      this.categoryDialog.form = {
        categoryName: "",
        categoryImage: "",
      };
      this.$nextTick(() => {
        this.$refs.categoryForm?.clearValidate();
      });
    },
    showEditCategory(row) {
      this.categoryDialog.visible = true;
      this.categoryDialog.isEdit = true;
      this.categoryDialog.editId = row.id;
      this.categoryDialog.form = {
        categoryName: row.categoryName || "",
        categoryImage: row.categoryImage || "",
      };
      this.$nextTick(() => {
        this.$refs.categoryForm?.clearValidate();
      });
    },
    saveCategory() {
      this.$refs.categoryForm.validate(async (valid) => {
        if (valid) {
          try {
            const params = {
              ...this.categoryDialog.form,
              // createTime: new Date().toISOString()
            };

            if (this.categoryDialog.isEdit) {
              params.id = this.categoryDialog.editId;
              await updateForumCategory(params);
              this.$message.success('编辑社区分类成功');
            } else {
              await addForumCategory(params);
              this.$message.success('新增社区分类成功');
            }

            this.categoryDialog.visible = false;
            this.getData();
          } catch (error) {
            console.error('保存社区分类失败:', error);
            this.$message.error('保存社区分类失败');
          }
        }
      });
    },
    handleDelete(row) {
      this.$confirm(`确定要删除社区分类"${row.categoryName}"吗？`, "提示", {
        type: "warning"
      }).then(async () => {
        try {
          await deleteForumCategory({ id: row.id });
          this.$message.success('删除社区分类成功');
          this.getData();
        } catch (error) {
          console.error('删除社区分类失败:', error);
          this.$message.error('删除社区分类失败');
        }
      }).catch(() => {
        // 用户取消删除
      });
    },
    // 图片上传相关方法
    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    async handleImageUpload(options) {
      try {
        const formData = new FormData();
        formData.append('file', options.file);

        const res = await upload(formData);

        // if (res.data && res.data[0] && res.data[0].fileName) {
        //   const serverUrl = `https://www.yaozhuasocial.com/imgs/${res.data[0].fileName}`;
        if (res.data && res.data) {
          const serverUrl = res.data;
          this.categoryDialog.form.categoryImage = serverUrl;
          this.$message.success('图片上传成功');
        } else {
          this.$message.error('上传响应格式错误');
        }
      } catch (error) {
        console.error('上传失败:', error);
        this.$message.error('图片上传失败，请重试');
      }
    },
    removeImage() {
      this.categoryDialog.form.categoryImage = "";
      this.$message.success('图片已删除');
    },
  },
};
</script>

<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.2s;
    width: 120px;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      border-color: #409eff;
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  display: block;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
}

.close-btn {
  position: absolute;
  top: 2px;
  right: 2px;
  color: #fff;
  background: rgba(0, 0, 0, 0.4);
  border-radius: 50%;
  font-size: 16px;
  cursor: pointer;
  z-index: 2;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background: rgba(0, 0, 0, 0.6);
  }
}

::v-deep .el-date-editor {
  margin-right: 10px;
  width: 300px;
}
</style>